package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"video-hub/model/cache"
	"video-hub/model/mysql"

	"video-hub/videorpc/internal/svc"
	"video-hub/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *videorpc.RegisterRequest) (*videorpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	err := user.FindUserPhone(mysql.DB, in.PhoneNum)
	if err != nil {
		return nil, err
	}
	if user.ID != 0 {
		return nil, errors.New("用户已经存在")
	}
	result, _ := cache.Rdb.Get(l.ctx, "send"+in.PhoneNum).Result()
	if in.SendSms != result {
		return nil, errors.New("短信验证码不正确")
	}
	user = mysql.User{
		PhoneNum:      in.PhoneNum,
		Password:      in.Password,
		NickName:      fmt.Sprintf("游客_%d", rand.Intn(10000)),
		Url:           "C:\\Users\\ZhuanZ\\Pictures\\Screenshots\\OIP-C.webp",
		AccountStatus: 0,
	}
	err = user.RegisterUser(mysql.DB)
	if err != nil {
		return nil, err
	}
	return &videorpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
